<template>
  <ArtSearchBar
    ref="searchBarRef"
    v-model="formData"
    :items="formItems"
    :rules="rules"
    @reset="handleReset"
    @search="handleSearch"
  >
  </ArtSearchBar>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  const props = defineProps({
    modelValue: { type: Object, default: () => ({}) },
    resourceTypeList: { type: Array, default: () => [] },
    categories: { type: Array, default: () => [] }
  })
  const emit = defineEmits(['update:modelValue', 'search', 'reset'])

  const searchBarRef = ref()

  const formData = computed({
    get: () => props.modelValue || {},
    set: (val) => emit('update:modelValue', val)
  })

  const categoryOptions = computed(() => {
    const list =
      Array.isArray(props.resourceTypeList) && props.resourceTypeList.length
        ? props.resourceTypeList
        : Array.isArray(props.categories)
          ? props.categories
          : []
    return list.map((c: any) => ({ label: c.name, value: c.id }))
  })

  const rules = {}
  const statusOptions = ref([
    { label: '所有', value: '' },
    { label: '前台', value: 1 },
    { label: '后台', value: 2 },
    { label: 'API', value: 3 }
  ])

  const formItems = computed(() => [
    { label: '搜索', key: 'search', type: 'input', placeholder: '请输入搜索内容', clearable: true },
    {
      label: '所属应用',
      key: 'app',
      type: 'select',
      props: { placeholder: '请选择状态', options: statusOptions.value, clearable: true }
    },
    {
      label: '所属分类',
      key: 'cate_id',
      type: 'select',
      props: { placeholder: '请选择分类', options: categoryOptions.value, clearable: true }
    },
    {
      label: '创建日期',
      key: 'daterange',
      type: 'datetime',
      props: {
        style: { width: '100%' },
        placeholder: '请选择日期范围',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  ])

  const handleReset = () => emit('reset')

  const handleSearch = async () => {
    // 如果有 validate 方法则校验，否则直接 emit
    if (searchBarRef.value && typeof searchBarRef.value.validate === 'function') {
      await searchBarRef.value.validate().catch(() => {})
    }
    emit('search', formData.value)
  }
</script>
